package com.jojo.conf;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author hpl
 * @since 2024/12/6
 */
@Slf4j
public class MyWebSocketHandler extends TextWebSocketHandler {

    private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        System.out.println("WebSocket连接已建立！！！");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 广播收到的消息给所有客户端
        for (WebSocketSession webSocketSession : sessions) {
            if (webSocketSession.isOpen()) {
                webSocketSession.sendMessage(message);
            }
        }
    }

//    @Override
//    public void handleBinaryMessage(WebSocketSession session, BinaryMessage message){
//        try {
//            byte[] imageBytes = message.getPayload().array();
//            for (WebSocketSession webSocketSession : sessions) {
//                if (webSocketSession.isOpen()) {
//                    webSocketSession.sendMessage(new BinaryMessage(imageBytes));
//                }
//            }
//        }catch (Exception e) {
//            log.error("发送图片失败");
//        }
//    }

    @Override
    public void handleBinaryMessage(WebSocketSession session, BinaryMessage message){
        try {
            byte[] imageBytes = message.getPayload().array();
            String imageDataUrl = "data:image/png;base64," + java.util.Base64.getEncoder().encodeToString(imageBytes);
            for (WebSocketSession webSocketSession : sessions) {
                if (webSocketSession.isOpen()) {
                    webSocketSession.sendMessage(new TextMessage(imageDataUrl));
                }
            }
        }catch (Exception e) {
            log.error("发送图片失败");
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
        System.out.println("WebSocket连接已关闭！！！");
    }
}
